package com.hongxun.budget.ui.activity.tk;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.BMaterialEntityDao;
import com.hongxun.budget.greendao.BPointConfigEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.adapter.SpinnerOffBgAdapter;
import com.hongxun.budget.ui.dialog.MaterialInputDialog;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.BPointConfigEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 添加材料
 */
public class AddMaterialActivity extends BaseActivity {


    @BindView(R.id.center_spinner)
    Spinner centerSpinner;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.search_info)
    EditText searchInfo;
    @BindView(R.id.list2)
    RecyclerView list2;
    DaoSession session;

    List<String> leftDatas = new ArrayList<>();
    SuperAdapter<String> leftAdapter;
    int left = 0;//记录left的选择
    List<BMaterialEntity> deviceEntities = new ArrayList<>();
    SuperAdapter<BMaterialEntity> rightAdapter;
    String label, label2, search, intentLabel;
    @BindView(R.id.right_save)
    Button rightSave;

    List<BMaterialEntity> result = new ArrayList<>();

    boolean isChange=false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_material;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        isChange=getIntent().getBooleanExtra("change",false);
        rightSave.setText("确定");
        rightSave.setVisibility(View.VISIBLE);
        intentLabel = getIntent().getStringExtra("label");
        session = GreenDaoManager.getInstance().getmDaoSession();
        final BPointConfigEntity b = session.getBPointConfigEntityDao().queryBuilder()
                .where(BPointConfigEntityDao.Properties.PCLive.eq(intentLabel), BPointConfigEntityDao.Properties.PCProcess.eq("0")).unique();
        List<String> labels = new ArrayList<>();
        if (b != null)
            labels = Arrays.asList(b.getPCLabel().split(","));
        else
            T.showLong(context, "该点位缺少配置，请联系管理员");
        centerSpinner.setAdapter(new SpinnerOffBgAdapter<String>(context, labels, centerSpinner)
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        searchInfo.setText("");
                        left = 0;
                        label = (String) data[1];
                        leftDatas.clear();
                        deviceEntities.clear();
                        setLeftList();
                    }
                }));
        list.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        list.setAdapter(leftAdapter = new SuperAdapter<String>(R.layout.content_adddevice_left) {
            @Override
            public void bindView(ViewHolder viewHolder, final String s, final int i) {
                TextView t = viewHolder.getView(R.id.label);
                t.setText(s);
                if (i == left) {
                    t.setBackgroundResource(R.drawable.view_bottom_textpre);
                } else {
                    t.setBackgroundResource(R.color.white);
                }
                t.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        searchInfo.setText("");
                        left = i;
                        label2 = s;
                        leftAdapter.notifyDataSetChanged();
                        setRightList();
                    }
                });
            }
        });
        leftAdapter.setData(leftDatas);
        leftAdapter.setEmptyDataView(R.layout.view_empty);
        list2.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list2.setAdapter(rightAdapter = new SuperAdapter<BMaterialEntity>(R.layout.content_add_material) {
            @Override
            public void bindView(ViewHolder viewHolder, final BMaterialEntity bDeviceEntity, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(bDeviceEntity.getMName());
//                ((TextView) viewHolder.getView(R.id.type)).setText(bDeviceEntity.getMLabel());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(bDeviceEntity.getMParameter());
                viewHolder.getView(R.id.layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new MaterialInputDialog().setB(bDeviceEntity).setListener(new ResponseListener() {
                            @Override
                            public void response(Object... data) {
                                BMaterialEntity b = (BMaterialEntity) data[0];
                                result.add(b);
                                if(isChange){
                                    Intent intent = new Intent();
                                    intent.putExtra("material", (Serializable) result);
                                    setResult(Activity.RESULT_OK, intent);
                                    finish();
                                }else{
                                    T.showLong(context, b.getMName() + "\n材料已添加到已选列表");
                                }
                            }
                        }).show(getFragmentManager(), "");
                    }
                });
            }
        });
        rightAdapter.setData(deviceEntities);
        rightAdapter.setEmptyDataView(R.layout.view_empty);
        if (labels.size() > 0) {
            label = labels.get(0);
            setLeftList();
        }
    }

    void setLeftList() {
        BPointConfigEntity l = session.getBPointConfigEntityDao().queryBuilder()
                .where(BPointConfigEntityDao.Properties.PCLive.eq(label), BPointConfigEntityDao.Properties.PCProcess.eq("1")).unique();
        if (l != null && !TextUtils.isEmpty(l.getPCLabel()))
            leftDatas.addAll(Arrays.asList(l.getPCLabel().split(",")));
        leftAdapter.notifyDataSetChanged();
        if (leftDatas.size() > 0) {
            label2 = leftDatas.get(0);
            setRightList();
        } else rightAdapter.notifyDataSetChanged();
    }

    void setRightList() {
        search = searchInfo.getText().toString();
        QueryBuilder<BMaterialEntity> builder = session.getBMaterialEntityDao().queryBuilder();
        List<BMaterialEntity> entities = builder.where(BMaterialEntityDao.Properties.MMidtype.eq(label), BMaterialEntityDao.Properties.MLabel.eq(label2)
                , builder.or(BMaterialEntityDao.Properties.MName.like("%" + search + "%"), BMaterialEntityDao.Properties.MParameter.like("%" + search + "%"))).list();
        deviceEntities.clear();
        deviceEntities.addAll(entities);
        rightAdapter.notifyDataSetChanged();
    }


    @OnClick({R.id.right_save, R.id.search_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_save:
                Intent intent = new Intent();
                intent.putExtra("material", (Serializable) result);
                setResult(Activity.RESULT_OK, intent);
                finish();
                break;
            case R.id.search_button:
                setRightList();
                break;
        }
    }
}
